from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from collections import defaultdict
from app.controllers.appointment.list import appointment_list_controller
from app.controllers.appointment.space import appointment_space_controller
from app.models import AppointmentDesigner, AppointmentList
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.saas import *
from datetime import datetime, timedelta
from app.controllers.appointment.designer import appointment_designer_controller

saas_appointment_router = APIRouter()
model_name = "预约"

@saas_appointment_router.get("/3month", summary=f"查看{model_name}列表")
async def do_settings_3month(
        month: str = Query("", description="月份"),
        space_id: int = Query(1, description="门店id"),
):
    if month == "":
        now_month = datetime.now().strftime("%Y-%m")
    else:
        now_month = month

    year = int(now_month.split("-")[0])  # 提取年份
    month = int(now_month.split("-")[1])  # 提取月份
    prev_month, current_month, next_month = await get_month_range(year, month)

    # 查询前一个月的预约数据
    prev_month_appointments = await AppointmentList.filter(
        time__gte=prev_month,
        time__lt=current_month,
        space_id=space_id
    ).values("time")

    # 查询当月的预约数据
    current_month_appointments = await AppointmentList.filter(
        time__gte=current_month,
        time__lt=next_month,
        space_id=space_id
    ).values("time")

    # 查询后一个月的预约数据
    next_month_appointments = await AppointmentList.filter(
        time__gte=next_month,
        time__lt=next_month + timedelta(days=31),
        space_id=space_id
    ).values("time")

    # 统计每天的预约数量
    def count_appointments(appointments):
        count_dict = defaultdict(int)
        for appointment in appointments:
            date = appointment["time"].strftime('%Y-%m-%d')  # 提取日期部分
            count_dict[date] += 1
        return [{"date": date, "nums": nums} for date, nums in count_dict.items()]

    # 合并结果
    result = []
    result.extend(count_appointments(prev_month_appointments))
    result.extend(count_appointments(current_month_appointments))
    result.extend(count_appointments(next_month_appointments))

    return SuccessExtra(data=result)

async def get_month_range(year, month):
    """获取指定年月的第一天和最后一天"""
    if month == 1:
        prev_month = datetime(year - 1, 12, 1)
    else:
        prev_month = datetime(year, month - 1, 1)

    if month == 12:
        next_month = datetime(year + 1, 1, 1)
    else:
        next_month = datetime(year, month + 1, 1)

    current_month = datetime(year, month, 1)
    return prev_month, current_month, next_month

@saas_appointment_router.get("/list", summary=f"查看{model_name}列表")
async def do_settings_list(
        date: str = Query("", description="日期"),
        space_id: int = Query(1, description="门店id"),
):
    if date == "":
        date = datetime.now().strftime("%Y-%m-%d")

    space = await appointment_space_controller.do_detail(space_id)
    start = space['start']
    end = space['end']
    interval = space['interval']
    times_all = generate_time_slots(start=start, end=end, interval=interval)

    data_appointment = await AppointmentDesigner.filter(space_id__contains=[space_id]).values("id","name")
    for item in data_appointment:
        item["ap_con"] = []
        designer_id = item["id"]
        q = Q(time__contains=date,designer_ids__contains=[designer_id],space_id=space_id)
        total,data_ap_designer = await appointment_list_controller.do_list(page=1,page_size=100,search=q,order_by="time")
        width = 80
        left_last = 0
        if data_ap_designer:
            for ap_item in data_ap_designer:
                if ap_item["longs"]>0:
                    width = ap_item["longs"]/interval * 80
                left = calculate_intervals(start, ap_item["time"], interval)

                ap_item["width"] = width
                ap_item["left"] = left * 80 - left_last
                print(f"{ap_item['id']}计算间隔为：{ap_item["left"]},{left_last}")
                left_last = ap_item["left"] + width

            item["ap_con"] = data_ap_designer
    data = {
        "head":times_all,
        "list": data_appointment
    }
    return SuccessExtra(data=data)

def generate_time_slots(start, end, interval):
    # 将开始时间和结束时间转换为 datetime 对象
    start_time = datetime.strptime(start, '%H:%M')
    end_time = datetime.strptime(end, '%H:%M')

    # 初始化时间列表
    time_slots = []

    # 循环生成时间点
    current_time = start_time
    while current_time < end_time:
        # 将时间点添加到列表
        time_slots.append(current_time.strftime('%H:%M'))
        # 增加时间间隔
        current_time += timedelta(minutes=interval)

    return time_slots

def calculate_intervals(start, target_time_str, interval):

    # 1. 将 target_time_str 转换为 datetime 对象
    target_time  = datetime.strptime(target_time_str, "%Y-%m-%d %H:%M:%S")

    # 2. 将 start 转换为 datetime 对象，并将日期部分设置为 target_time 的日期
    start_time = datetime.strptime(start, "%H:%M").replace(
        year=target_time.year,
        month=target_time.month,
        day=target_time.day
    )

    # 3. 如果 start_time 晚于 target_time，说明 start_time 是前一天的
    if start_time > target_time:
        start_time -= timedelta(days=1)

    # 4. 计算时间差
    time_diff = target_time - start_time

    # 4. 将时间差转换为分钟
    total_minutes = time_diff.total_seconds() / 60

    # 5. 计算间隔数
    interval_count = int(total_minutes // interval)

    return interval_count
